package com.jojo.playwright;

import com.microsoft.playwright.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * @author yangyun
 * @project jdBuy
 * @description:
 * @date 2024-11-21 16:31
 */
public class PlayWrightUtils {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            BrowserType chromium = playwright.chromium();
            Browser browser = chromium.launch();
            Page page = browser.newPage();
            // re.jd.com  https://www.taobao.com/  https://pro.jd.com/mall/active/4U4aC6LY2b3wMJKEFfwqqZktpBYH/index.html
            String url = "https://www.jd.com/?cu=true&utm_source=baidu-pinzhuan&utm_medium=cpc&utm_campaign=t_288551095_baidupinzhuan&utm_term=0f3d30c8dba7459bb52f2eb5eba8ac7d_0_02429f49a3354107a2ad393a88c855c9/";
            String url1 = "https://pro.jd.com/mall/active/4U4aC6LY2b3wMJKEFfwqqZktpBYH/index.html";
            page.navigate(url1); // https://news.baidu.com/
            String content = page.content();
            System.out.println(page.content());
            String title = page.title();
            Document document = Jsoup.parse(content);
            Element body = document.body();
            Elements links = document.select("a[href]");
            Element first = links.first();
            String href = first.attr("href");
            String s = fetchContent("https:" + href);


            Page newPage = browser.newPage();
            Response navigate = newPage.navigate("https:" + href);
            System.out.println("======================");
            System.out.println(newPage.content());
            ElementHandle a = newPage.querySelector("a");
//            a.click();

            Locator submit = page.getByText("Submit");
            submit.hover();
            submit.click();


//            browser.close();
                    ;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String fetchContent(String url) throws IOException {
        URL u = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) u.openConnection();

        // 设置连接超时时间
        connection.setConnectTimeout(5000);

        // 设置读取超时时间
        connection.setReadTimeout(5000);

        // 发送 GET 请求
        connection.connect();

        // 读取响应内容
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 返回响应内容
        return response.toString();
    }
}
